package com.example.hospital_208.controller;

import com.example.hospital_208.po.Doctor;
import com.example.hospital_208.po.User;
import com.example.hospital_208.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 查询所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.listUsers();
    }

    // 根据ID查询用户
    @GetMapping("/{user_id}")
    public User getUser(@PathVariable Integer user_id) {
        return userService.getUserById(user_id);
    }

    // 根据用户名查询用户（登录接口）
    @PostMapping("/login")
    public User login(@RequestParam String user_name, @RequestParam String password) {
        User user = userService.getUserByUsername(user_name);
        if (user != null && user.getPassword().equals(password)) {
            userService.updateLoginStatus(user.getUser_id()); // 更新登录状态
            return user;
        }
        return null;
    }

    // 新增用户
    @PostMapping
    public String addUser(@RequestBody User user) {
        int result = userService.addUser(user);
        return result > 0 ? "用户添加成功" : "用户添加失败";
    }

    // 更新用户信息
    @PutMapping
    public String updateUser(@RequestBody User user) {
        int result = userService.updateUser(user);
        return result > 0 ? "用户信息更新成功" : "用户信息更新失败";
    }

    // 删除用户
    @DeleteMapping("/{user_id}")
    public String deleteUser(@PathVariable Integer user_id) {
        int result = userService.deleteUser(user_id);
        return result > 0 ? "用户删除成功" : "用户删除失败";
    }

    // 修改密码接口
    @PutMapping("/{user_id}/password")
    public String updatePassword(@PathVariable Integer user_id, @RequestParam String newPassword) {
        int result = userService.updatePassword(user_id, newPassword);
        return result > 0 ? "密码修改成功" : "密码修改失败";
    }

    // 通过 user_name 查询 doctor 表的信息
    @GetMapping("/doctor/{user_name}")
    public Doctor getDoctorByUserName(@PathVariable String user_name) {
        return userService.getDoctorByUserName(user_name);
    }
}